from app_detail.waihui_track.model_node import JiaoyiAccount
from app_detail.waihui_track.model_node import ShouhuiAccount
from app_detail.waihui_track.model_node import WaiguoAccount
from anytree import Node, RenderTree, LevelOrderGroupIter

from my_tools.df_data_utils import is_none_null


def show_node_tree(node: Node):
    # 可视化整个树
    for pre, fill, node in RenderTree(node):
        show_name = node.myobj.name
        if is_none_null(show_name):
            show_name = "(未知)"
        if isinstance(node.myobj, WaiguoAccount):
            print(f"{pre}{show_name[:10]} ${node.myobj.transfer_amount_usd}")
        elif isinstance(node.myobj, ShouhuiAccount):
            print(f"{pre}{show_name} ${node.myobj.amount_usd}")
        elif isinstance(node.myobj, JiaoyiAccount) and isinstance(node.parent.myobj, ShouhuiAccount):
            print(f"{pre}{show_name} ${node.myobj.amount_usd}/¥{node.myobj.amount}")
        elif isinstance(node.myobj, JiaoyiAccount):
            print(f"{pre}{show_name} ¥{node.myobj.amount}")


def show_node_tree_to_file(node: Node, output_file, append=False):
    # 打开文件，准备写入或追加写入
    mode = 'a' if append else 'w'
    with open(output_file, mode) as file:
        # 可视化整个树
        for pre, fill, node in RenderTree(node):
            show_name = node.myobj.name
            if is_none_null(show_name):
                show_name = "(未知)"
            if isinstance(node.myobj, WaiguoAccount):
                file.write(f"{pre}{node.myobj.transfer_time} {show_name[:10]} ${node.myobj.transfer_amount_usd}\n")
            elif isinstance(node.myobj, ShouhuiAccount):
                file.write(f"{pre}{node.myobj.receipt_date} {show_name} ${node.myobj.amount_usd}\n")
            elif isinstance(node.myobj, JiaoyiAccount) and isinstance(node.parent.myobj, ShouhuiAccount):
                file.write(f"{pre}{node.myobj.end_receipt_date} {show_name} ${node.myobj.amount_usd}/¥{node.myobj.amount}\n")
            elif isinstance(node.myobj, JiaoyiAccount):
                file.write(f"{pre}{node.myobj.end_receipt_date} {show_name} ¥{node.myobj.amount}\n")


def get_tree_depth(root):
    depth = 0
    for group in LevelOrderGroupIter(root):
        depth += 1
    return depth
